#! /bin/igawk -f

@include ./awk_common/common_funs.awk

BEGIN{
  FS="[, \t]"; 
  OFS=",";	

idx[0]="iPod";
idx[1]="flash";
idx[2]="winpad";
idx[3]="winphone";
idx[4]="aphone";
idx[5]="apad";
idx[6]="ott";
idx[7]="iPhone";
idx[8]="iPad";
idx[9]="tv";  

idx_isp[0]="telecom"
idx_isp[1]="unicom"
idx_isp[2]="overseas"
idx_isp[3]="HK_MO_TW"
idx_isp[4]="other"
  
}

NR==FNR {  ;# 
        ip_begin[k] = $1 
        ip_end[k] = $2
        record[k]=$0
        province[k]=$3  
        provider[k]=$4     
        k++; 
}  

NR>FNR {
  cip=$1;
  ipset[cip]++; 
  
  ip_int=get_ip_int(cip);
  peer_idx=binary_search_ip(ip_begin,ip_end,ip_int);
  provider_name=provider[peer_idx];
  if(provider_name == "联通"){
    provider_name="unicom"
  } else if(provider_name == "电信"){
    provider_name="telecom"
  } else if(provider_name == "其它"){
    provider_name="HK_MO_TW"
  } else if(provider_name == "NULL"){
    provider_name="overseas"
  } else{
    provider_name = "other";
  }
  # printf("%16s %-10d %d\t%s\t%s\n", cip, ip_int, peer_idx, provider[peer_idx], provider_name);
  rec_isp[provider_name]++;


#  print $4;	
  split($4,field,"[?=_]");
  
  platform=field[4];
  
  rec[platform]++;

  if(index($4, "&ok=0")) 
  {
      ok[platform]++;
      ok_isp[provider_name]++;
  } 
  else
  {
    pos=index($4, "&btm=")
    if(pos) 
    {
      pos+=5;
      tmp=substr($4, pos);
      pos1=index(tmp, "&");
      btm=substr(tmp, 0, pos1-1);
      if(btm/1000>30)
      {
        fail[platform]++;   
        fail_isp[provider_name]++;
      }
    }        
  }

}
END{
  #print FILENAME	
  id=split(FILENAME,m,"/");

  file_name=m[id];

  split(file_name,n,".");
  timestamp=n[1];

  printf("%s,IP,%d\n",timestamp,length(ipset));
  for(i=0;i<10;i++){
    ok_radio=0.0
    fail_radio=0.0
    if(rec[idx[i]] > 0) {
      ok_radio=(100 * ok[idx[i]] / rec[idx[i]]);
      fail_radio=(100 * fail[idx[i]] / rec[idx[i]]);
    }
    printf("%s,%s,%d\n",timestamp, idx[i], rec[idx[i]]);  
    printf("%s,%s_ok,%.2f\n",timestamp, idx[i], ok_radio);  
    printf("%s,%s_fail,%.2f\n",timestamp, idx[i], fail_radio);  	
  }  	
  for(i=0;i<5;i++){
    ok_radio=0.0
    fail_radio=0.0
    if(rec_isp[idx_isp[i]] > 0) {
      ok_radio=(100 * ok_isp[idx_isp[i]] / rec_isp[idx_isp[i]]);
      fail_radio=(100 * fail_isp[idx_isp[i]] / rec_isp[idx_isp[i]]);
    }
    printf("%s,%s,%d\n",timestamp, idx_isp[i], rec_isp[idx_isp[i]]);  
    printf("%s,%s_ok,%.2f\n",timestamp, idx_isp[i], ok_radio);  
    printf("%s,%s_fail,%.2f\n",timestamp, idx_isp[i], fail_radio);        
  }
}
